package org.smart4j.framework.common.aop.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理（JDK版本）
 * 缺陷：被代理类必须要实现接口
 *
 * @author YooLin1c
 * @version 1.0.0
 * @since 2018-01-31 16:46
 */
public class JDKDynamicProxy implements InvocationHandler {
    private Object target;

    private JDKDynamicProxy() {
    }

    @SuppressWarnings("unckecked")
    public <T> T proxy(Object target) {
        this.target = target;
        return (T) Proxy.newProxyInstance(
                this.target.getClass().getClassLoader(),
                this.target.getClass().getInterfaces(),
                this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object result = method.invoke(this.target, args);
        after();
        return result;
    }

    private void before() {
        System.out.println("before");
    }

    private void after() {
        System.out.println("after");
    }

    public static JDKDynamicProxy getInstance() {
        return DynamicProxyHolder.INSTANCE;
    }

    private static class DynamicProxyHolder {
        private static final JDKDynamicProxy INSTANCE = new JDKDynamicProxy();
    }
}
